package com.chinasofti.optional;

import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Supplier;

public class Demo03 {
    public static void main(String[] args) {
        //method1();
        //method2();
        Student s = new Student("lilei",18);
        //s = null;
        Optional<Student> optional = Optional.ofNullable(s);
        //如果不为空执行给定操作，如果为空不执行任何操作；
        optional.ifPresent(new Consumer(){
            @Override
            public void accept(Object o) {
                Student s1 = (Student)o;
                System.out.println("s1 = " + s1);
            }

        });
    }

    private static void method2() {
        Student s = new Student("lilei",18);
        s = null;
        Optional<Student> optional = Optional.ofNullable(s);
        //optional 不为空，返回具体指，为空 则返回函数中产生的值
        optional.orElseGet(new Supplier(){

            @Override
            public Object get() {
                return new Student("lili",11);
            }
        });
        //optional.orElseGet(()->new Student("lili1",17));
        System.out.println("optional = " + optional);
    }

    private static void method1() {
        Student s = new Student("lilei",18);
        s = null;
        Optional<Student> optional = Optional.ofNullable(s);
        //optional 不为空，返回具体指，为空 则返回参数中的值
        Student st = optional.orElse(new Student("lili",12));
        System.out.println("st = " + st);
    }


}
